package com.launcher.wkang.receive;

import java.lang.reflect.Method;
import java.util.ArrayList;

import com.android.internal.telephony.ITelephony;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.util.Log;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.internal.telephony.ITelephony;//见第二点
import com.launcher.wkang.App;

import android.telephony.SmsMessage;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PhoneStatReceiver extends BroadcastReceiver{

    private TelephonyManager telephonyManager;

    private final String PHONE_RECEIVER_ACTION ="android.intent.action.PHONE_STATE";
    private final String MSM_RECEIVER_ACTION ="android.provider.Telephony.SMS_RECEIVED";
    String TAG = "tag";
    TelephonyManager telMgr;
    @Override
    public void onReceive(Context context, Intent intent) {

        telephonyManager = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
        telMgr = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);

        String action = intent.getAction();
        if(PHONE_RECEIVER_ACTION.equals(action)) {

            switch (telMgr.getCallState()) {
                case TelephonyManager.CALL_STATE_RINGING:
//                    上课禁用时间禁止打电话
                    if (!App.getINstance().isAnswer){
                        endCall();
                    }
                    String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
                    Log.v(TAG, "number:" + number);
                    ArrayList<String> phones=getPhoneNum(context);
                    if (!phones.contains(number)) {

                        endCall();
                    }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    break;
            }
        }else if(MSM_RECEIVER_ACTION.equals(action)){
            messageInfo(context,intent);
        }

    }
    /**
     * 挂断电话
     */
    private void endCall()
    {
        Class<TelephonyManager> c = TelephonyManager.class;
        try
        {
            Method getITelephonyMethod = c.getDeclaredMethod("getITelephony", (Class[]) null);
            getITelephonyMethod.setAccessible(true);
            ITelephony iTelephony = null;
            Log.e(TAG, "End call.");
            iTelephony = (ITelephony) getITelephonyMethod.invoke(telMgr, (Object[]) null);
            iTelephony.endCall();
        }
        catch (Exception e)
        {
            Log.e(TAG, "Fail to answer ring call.", e);
        }
    }
    private ArrayList<String>  getPhoneNum(Context context) {
        ArrayList<String> numList = new ArrayList<String>();
        //得到ContentResolver对象
        ContentResolver cr = context.getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        while (cursor.moveToNext())
        {
            // 取得联系人ID
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
            // 取得电话号码(可能存在多个号码)
            while (phone.moveToNext())
            {
                String strPhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                numList.add(strPhoneNumber.replaceAll(" ",""));
                Log.v("tag","strPhoneNumber:"+strPhoneNumber);
            }

            phone.close();
        }
        cursor.close();
        return numList;
    }

    //参照网上的代码拦截短信
    private void messageInfo(Context context, Intent intent){
        //获取intent参数
        Bundle bundle=intent.getExtras();
        //判断bundle内容
        if (bundle!=null)
        {
            //取pdus内容,转换为Object[]
            Object[] pdus=(Object[])bundle.get("pdus");
            String format = intent.getStringExtra("format");
            //解析短信
            SmsMessage[] messages = new SmsMessage[pdus.length];
            for(int i=0;i<messages.length;i++){
                byte[] pdu=(byte[])pdus[i];
                messages[i]=SmsMessage.createFromPdu(pdu);
            }
            //解析完内容后分析具体参数
            for(SmsMessage msg:messages) {
                //获取短信内容
                String content=msg.getMessageBody();
                String sender=msg.getOriginatingAddress();
                ArrayList<String> phones=getPhoneNum(context);
                if (!phones.contains(sender)){
                    abortBroadcast();
                    return;
                }
                Date date = new Date(msg.getTimestampMillis());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String sendTime = sdf.format(date);
                Log.i("PhoneReceiver","电话["+sender+"] 内容："+content+"时间："+sendTime);

            }

        }
    }
}


